package com.bankcomm.luafuction;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.keplerproject.luajava.LuaException;
import org.keplerproject.luajava.LuaState;

import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.text.TextUtils;

import com.bankcomm.common.ConfigManager;
import com.rytong.tools.offstore.OffStoreDownload;
import com.rytong.tools.ui.Component;
import com.rytong.tools.utils.Utils;

public class LuaAudio {
	/**
	 * 本地音频播放时候的音乐ID。
	 */
    int soundID;

    public LuaAudio() {
        try {
            Component.LUASTATE.pushObjectValue(this);
            Component.LUASTATE.setGlobal("luaaudio");
            final String luahead = "audio = {}; ";
            final String luafc1 = "function audio:load(soundname) local a1 = luaaudio:load(soundname); return a1; end;";
            final String luafc2 = "function audio:dispose(soundPool) luaaudio:dispose(soundPool); end;";
            final String luafc3 = "function audio:play(soundPool, numberOfLoops) luaaudio:play(soundPool, numberOfLoops); end;";
            final String luafc4 = "function audio:stop(soundPool) local a1 = luaaudio:stop(soundPool);  return a1; end;";
            final String luafc5 = "function audio:pause(soundPool) local a1 = luaaudio:pause(soundPool);  return a1; end;";
            final String luafc6 = "function audio:resume(soundPool) local a1 = luaaudio:resume(soundPool);  return a1; end;";
            final String luafc7 = "function audio:getMaxVolume(soundPool) local a1 = luaaudio:getMaxVolume(soundPool);  return a1; end;";
            final String luafc8 = "function audio:getMinVolume(soundPool) local a1 = luaaudio:getMinVolume(soundPool);  return a1; end;";
            final String luafc9 = "function audio:getVolume(soundPool) local a1 = luaaudio:getVolume(soundPool);  return a1; end;";
            final String luafc10 = "function audio:setVolume(soundPool, volume) local a1 = luaaudio:setVolume(soundPool, volume); return a1; end;";
            Component.LUASTATE.gc(LuaState.LUA_GCCOLLECT, 0);
            Component.LUASTATE.LdoString(luahead.concat(luafc1).concat(luafc2).concat(luafc3).concat(luafc4)
                    .concat(luafc5).concat(luafc6).concat(luafc7).concat(luafc8).concat(luafc9).concat(luafc10));

        } catch (LuaException e) {
            // TODO Auto-generated catch block
            Utils.printException(e);
        }
    }
    /**
     * 加载音频文件
     * 
     * @param soundname
     * @return
     */
    public Object load(String soundname) {
    	if(TextUtils.isEmpty(soundname)){
    		return null;
    	}
        int mMaxStreams = 8;
        SoundPool mSoundPool = new SoundPool(mMaxStreams, AudioManager.STREAM_MUSIC, 0);
        try {
        	if(soundname.startsWith("/")){ // 网络音频。
        		soundname = soundname.substring(soundname.lastIndexOf("/") + 1, soundname.length());
        		String sourceUrl = ConfigManager.SERVER_URI.concat(soundname);// 下载地址
        		
        		String path = Utils.downloadAndSaveFile(sourceUrl , soundname);
        		if(!TextUtils.isEmpty(path)){//文件下载成功
        			soundID = mSoundPool.load(path, 1);
        		} else {
        			// 没有拿到音频资源。
        			mSoundPool = null;
        		}
        	} else { // 本地音频。
        		Object  object= Utils.getLocalFilePath(soundname);
        		if(object != null){
        		    if(object instanceof String){
        		        String path = (String)object;
        		        soundID = mSoundPool.load(path , 1);
        		    } else if(object instanceof AssetFileDescriptor){
        		        soundID = mSoundPool.load((AssetFileDescriptor)object, 1);
        		    }
        		} else {
        			// 没有拿到音频资源。
        			mSoundPool = null;
        		}
        	}
        }catch(Exception e){
        	//产生异常
        	mSoundPool = null;
        	Utils.printException(e);
        }
        return mSoundPool;
    }
    /**
     * 释放资源
     * @param soundPool
     */
    public void dispose(Object soundPool) {
        if (soundPool instanceof SoundPool) {
            SoundPool sp = (SoundPool) soundPool;
            sp.release();
        }
        soundPool = null;
    }

    public void play(Object soundPool,Object numberOfLoops) {
        if (soundPool instanceof SoundPool) {
            final SoundPool sp = (SoundPool) soundPool;
            int loopTmp = (Integer) numberOfLoops;
            if(loopTmp > 0){
                loopTmp --;
            }
            final int loop = loopTmp;
            int result = sp.play(soundID, 1.0f, 1.0f, 1, loop, 1.0f);
            if(result == 0){
                sp.setOnLoadCompleteListener(new OnLoadCompleteListener() { 
                    
                    @Override
                    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                        // TODO Auto-generated method stub
                        if(status == 0){
                        	sp.play(soundID, 1.0f, 1.0f, 1, loop, 1.0f);
                        }
                    }
                });
            }
        }
        
        
    }

    public Object stop(Object soundPool) {
        if (soundPool instanceof SoundPool) {
            SoundPool sp = (SoundPool) soundPool;
            sp.stop(soundID);
        }
        return null;
    }

    public Object pause(Object soundPool) {
        if (soundPool instanceof SoundPool) {
            SoundPool sp = (SoundPool) soundPool;
            sp.pause(soundID);
        }
        return null;
    }

    public Object resume(Object soundPool) {
        if (soundPool instanceof SoundPool) {
            SoundPool sp = (SoundPool) soundPool;
            sp.resume(soundID);
        }
        return null;
    }

    public int getMaxVolume(Object soundPool) {
        AudioManager am = (AudioManager) ConfigManager.currentView_
                .getSystemService(ConfigManager.currentView_.AUDIO_SERVICE);
        int audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        return audioMaxVolumn > 0 ? 100 : 0;
    }

    public int getMinVolume(Object soundPool) {
        return 0;
    }
    /**
     * 获得音量数值，以一个0～100的数字表示。
     * @param soundPool soundPool对象。
     * @return 一个数字，范围是0～100。
     */
    public int getVolume(Object soundPool) {
        AudioManager am = (AudioManager) ConfigManager.currentView_
                .getSystemService(ConfigManager.currentView_.AUDIO_SERVICE);
        int audioCurrentVolumn = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        // 计算百分比。
        float preVolume = (audioCurrentVolumn * 1.0f) / am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        // 取得百分数。
        int result = (int) (preVolume * 100);
        return result;
    }
    
    /**
     * 设置音乐音量。
     * 
     * @param soundPool soundPool对象。
     * @param volume 待设置的音量，范围：0～100。
     */
    public Object setVolume(Object soundPool, float volume) {
    	AudioManager am = (AudioManager) ConfigManager.currentView_
    		.getSystemService(ConfigManager.currentView_.AUDIO_SERVICE);
    	// 最大音量序号。
    	int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    	// 计算步长。各种机型的步长可能不一样。以100除以最大音量序号。
    	float stepVolume = 100.0f / maxVolume; // 得出每一阶段的音量index代表多少步长。
    	// 计算应该设置成多少序号。
    	int desVolumeIndex = (int) (volume / stepVolume);
    	desVolumeIndex = desVolumeIndex > maxVolume ? maxVolume : desVolumeIndex; // 最大值限制。
    	if(desVolumeIndex == 0 && volume != 0){ // 最小值修正。
    		desVolumeIndex++;
    	} else if(desVolumeIndex == maxVolume && volume != 100){ // 最大值修正。
    		desVolumeIndex--;
    	}
    	am.setStreamVolume(AudioManager.STREAM_MUSIC, desVolumeIndex, 0);
        return null;
    }
}
